window.onload = function(){
	const c = document.getElementById("canvas");
	c.width = window.innerWidth;
	c.height = 600;

	const ctx = c.getContext("2d");

	const environment = new Environment(c,ctx);
	//小鸟
	const bird = new Bird(250,260,ctx);
	//管道
	const pipes = [];

	setInterval(function(){
		let pipeSet = generateRandomPipe(ctx,c.width,c.height);
		pipes.push(pipeSet.top,pipeSet.bottom);
	},1600);

	gameLoop();

	function gameLoop(){
		ctx.fillRect(0,0,c.width,c.height);
		environment.update();
		environment.render();
		pipes.forEach(function(pipe1){
			pipe1.update();
			pipe1.render();
		})
		bird.update(pipes);
		bird.render();
		if(bird.dead){
			gameText(ctx,c,"被活活的撞死了");
			return;
		}
		if(bird.y >= 540){
			gameText(ctx,c,"被活活的摔死了");
			return;
		}
		window.requestAnimationFrame(gameLoop);
	}
}

function generateRandomPipe(ctx,canvasWidth,canvasHeight){
	let lengthTop = Math.round(Math.random()*200+100);
	let lengthBottom = canvasHeight - 220 - lengthTop;
	let img1 = document.getElementById("pipe1");
	let img2 = document.getElementById("pipe2");
	let returnVal = {};
	returnVal.top = new Pipe(ctx,canvasWidth,-5,lengthTop,4,img1);
	returnVal.bottom = new Pipe(ctx,canvasWidth,canvasHeight+5-lengthBottom,lengthBottom,4,img2);

	return returnVal;
}

function gameText(ctx,c,text){
	ctx.font = "130px Verdana";
	let w = ctx.measureText(text).width
	ctx.fillStyle = "red";
	ctx.fillText(text,(c.width-w)/2,c.height/2);
}